package top.yekongle.threadpool.common;

/**
 * @author Hank Lau
 * @date 2022/8/24
 */


import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import top.yekongle.threadpool.util.SpringUtils;
import top.yekongle.threadpool.util.ThreadUtil;

import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 *
 * @author ruoyi
 */
public class AsyncManager {
	/**
	 * 操作延迟10毫秒
	 */
	private final int OPERATE_DELAY_TIME = 10;

	/**
	 * 异步操作任务调度线程池
	 */
	private ScheduledExecutorService scheduledExecutor = SpringUtils.getBean("scheduledExecutorService");

	private ThreadPoolTaskExecutor asyncExecutor = SpringUtils.getBean("threadPoolTaskExecutor");

	/**
	 * 单例模式
	 */
	private AsyncManager() {
	}

	private static AsyncManager me = new AsyncManager();

	public static AsyncManager me() {
		return me;
	}

	/**
	 * 执行定时任务
	 *
	 * @param task 任务
	 */
	public void execute(TimerTask task) {
		scheduledExecutor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
	}

	public void execute(Runnable task) {
		asyncExecutor.execute(task);
	}

	/**
	 * 停止任务线程池
	 */
	public void shutdownScheduledExecutor() {
		ThreadUtil.shutdownAndAwaitTermination(scheduledExecutor);
	}
}